/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-11
 * Time: 17:57
 */

import java.util.PriorityQueue;

/**
 * 1:创建类，表示一个任务
 * Runnable 任务主体
 * time：任务执行的时间(换成了绝对的时间,也就是时间戳)
 */

class MyTimeTask implements Comparable<MyTimeTask>{
    public Runnable runnable;
    public long time;
    public MyTimeTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimeTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer{
    /**
     * 2:引入优先级队列来保存多个任务,省去了遍历的开销
     *
     */
    public PriorityQueue<MyTimeTask> queue=new PriorityQueue<>();
    /**
     * 3:引入扫描线程:
     * 不停的循环,获取到队首元素,判断是否到时间,
     * 到时间就执行,并且出队列,没到时间,就继续下一次循环
     */
    /**
     * 4:引入锁,针对队列的操作,加锁
     */
    Object locker=new Object();
public MyTimer() {


    Thread t = new Thread(() -> {
        synchronized (locker) {
            while (true) {
                if (queue.size() == 0) {
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                MyTimeTask myTimeTask = queue.peek();
                long time = System.currentTimeMillis();
                if (time >= myTimeTask.getTime()) {
                    myTimeTask.run();
                    queue.poll();
                } else {
                    try {
                        locker.wait( myTimeTask.getTime()-time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
    t.start();
}

    public   void schedule(Runnable runnable,long delay){
        synchronized(locker) {


            MyTimeTask myTimeTask = new MyTimeTask(runnable, delay);
            queue.offer(myTimeTask);
            locker.notify();
        }
    }

}
public class Test {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello  10000");
            }
        },10000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello  3000");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello  2000");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello  5000");
            }
        },5000);

    }
}
